﻿using System;
using System.Globalization;
using System.Linq;

namespace PsiIndexer {
  public class PsiChatInfo {
    private PsiChatInfo() {
      ID = Guid.NewGuid();
    }
    public Guid ID { get; private set; }
    public DateTime Time { get; set; }
    public ChatDirection Direction { get; set; }
    public string Text { get; set; }
    public string OriginalLine { get; set; }
    public PsiConversation Conversation { get; set; }
    public PsiChatInfo NextChat { get; set; }
    public PsiChatInfo PrevChat { get; set; }
    public string Author {
      get {
        switch (Direction) {
          case ChatDirection.FROM:
            return Conversation.Author.Split('@').FirstOrDefault();
          case ChatDirection.TO:
            return "basti";
          default:
            throw new ArgumentOutOfRangeException();
        }
      }
    }    
    
    public string Conversants {
      get {
        switch (Direction) {
          case ChatDirection.FROM:
            return string.Format("{0} => basti", Conversation.Author.Split('@').FirstOrDefault());
          case ChatDirection.TO:
            return string.Format("basti => {0}", Conversation.Author.Split('@').FirstOrDefault());
          default:
            throw new ArgumentOutOfRangeException();
        }
      }
    }

    public static PsiChatInfo Create(string logLine) {
      // catch wrong input
      if (string.IsNullOrEmpty(logLine)) {
        return null;
      }
      if (!logLine.Any(c => c == '|')) {
        return null;
      }

      string[] tokens = logLine.Split('|');
      string dateStr = tokens.ElementAtOrDefault(1);
      string dirStr = tokens.ElementAtOrDefault(3);
      DateTime dateTime;
      if (!DateTime.TryParseExact(dateStr, @"yyyy-MM-dd\THH:mm:ss", null, DateTimeStyles.None, out dateTime)) {
        return null;
      }

      var psi = new PsiChatInfo();
      psi.OriginalLine = logLine;
      // when the text contains |
      psi.Text = String.Join("|", tokens.Skip(5).ToArray());
      psi.Direction = dirStr.ToLower() == "from" ? ChatDirection.FROM : ChatDirection.TO;
      psi.Time = dateTime; // 2010-03-15T10:45:48

      return psi;
    }

    public  override string ToString() {
      return this.Text;
    }

    public override bool Equals(object obj) {
      var a = obj as PsiChatInfo;
      if (a != null) {
        return a.Time == this.Time && a.Text == this.Text && a.Conversation == this.Conversation;
      }
      return false;
    }
  }

  public enum ChatDirection {
    FROM,
    TO
  }
}